#!/usr/bin/env python3
# Copyright 2021 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import configparser
import logging
import time
import sys

ST2SVC = "st2stream"
DEFAULT_IP = "127.0.0.1"
DEFAULT_PORT = "9102"
ST2CFG = "/etc/st2/st2.conf"

# Systemd passes 3 paths to a generator, normal_dir, early_dir, late_dir.
default_paths = ["/tmp", "/tmp", "/tmp"]
for i, p in enumerate(sys.argv[1:]):
    default_paths[i] = p
EARLY_DIR, NORMAL_DIR, LATE_DIR = default_paths

LOG_TO_DISK = True
LOG_KW = {
    "level": logging.DEBUG,
    "format": "%(asctime)s - %(levelname)s - %(message)s",
}
if LOG_TO_DISK:
    LOG_KW["filename"] = f"{NORMAL_DIR}/{ST2SVC}_generator.log"

logging.basicConfig(**LOG_KW)
LOG = logging.getLogger()

LOG.debug(
    f"Systemd directories: Early='{EARLY_DIR}' Normal='{NORMAL_DIR}' Late='{LATE_DIR}'"
)

config = configparser.ConfigParser(strict=False)
config.read(ST2CFG)

section = ST2SVC[3:]
bind_address = config[section].get("host", DEFAULT_IP)
bind_port = config[section].get("port", DEFAULT_PORT)

contents = f"""[Unit]
# Generated by {sys.argv[0]} at {time.asctime(time.localtime())}
Description=StackStorm {ST2SVC} Socket.
PartOf={ST2SVC}.service
SourcePath={ST2CFG}

[Socket]
ListenStream={bind_address}:{bind_port}

[Install]
WantedBy=sockets.target
"""

with open(f"{NORMAL_DIR}/{ST2SVC}.socket", "w") as f:
    f.write(contents)

LOG.info(f"{ST2SVC} generated.")
